package com.docmgmt.mvp.controller;

import com.docmgmt.mvp.dto.AiChatRequest;
import com.docmgmt.mvp.dto.AiChatResponse;
import com.docmgmt.mvp.dto.AiFeedbackVO;
import com.docmgmt.mvp.dto.Result;
import com.docmgmt.mvp.dto.SubmitFeedbackRequest;
import com.docmgmt.mvp.entity.AiDialogEntity;
import com.docmgmt.mvp.exception.ForbiddenException;
import com.docmgmt.mvp.exception.UnauthorizedException;
import com.docmgmt.mvp.service.AiService;
import com.docmgmt.mvp.service.FeedbackService;
import com.docmgmt.mvp.service.PermissionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

/**
 * AI控制器（v3.0 SSE流式 + 对话历史 + 权限感知 + 反馈）
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/ai")
@RequiredArgsConstructor
@Tag(name = "AI服务", description = "AI问答、对话历史、反馈管理")
public class AiController {

    private final AiService aiService;
    private final PermissionService permissionService;
    private final FeedbackService feedbackService;

    /**
     * AI问答（非流式）
     *
     * POST /api/v1/ai/chat
     *
     * @param request 问答请求
     * @return 问答响应
     */
    @PostMapping("/chat")
    @Operation(summary = "AI问答（非流式）", description = "提交问题获取AI答案")
    public Result<AiChatResponse> chat(@Valid @RequestBody AiChatRequest request) {
        Long userId = getCurrentUserId();

        // 权限检查：ai:chat
        if (!permissionService.checkPermission(userId, "ai", "chat")) {
            throw new ForbiddenException("无权限使用AI问答");
        }

        log.info("POST /api/v1/ai/chat - userId={}, query={}", userId, request.getQuery());

        AiChatResponse response = aiService.chat(request, userId);

        log.info("AI问答成功: conversationId={}, responseTime={}s",
                response.getConversationId(), response.getResponseTime());

        return Result.success(response);
    }

    /**
     * AI问答（SSE流式响应）
     *
     * POST /api/v1/ai/chat/stream
     *
     * @param request 问答请求
     * @return SSE Emitter
     */
    @PostMapping("/chat/stream")
    @Operation(summary = "AI问答（SSE流式）", description = "流式返回AI答案")
    public SseEmitter chatStream(@Valid @RequestBody AiChatRequest request) {
        Long userId = getCurrentUserId();

        // 权限检查：ai:chat
        if (!permissionService.checkPermission(userId, "ai", "chat")) {
            throw new ForbiddenException("无权限使用AI问答");
        }

        log.info("POST /api/v1/ai/chat/stream - userId={}, query={}", userId, request.getQuery());

        return aiService.chatStream(request, userId);
    }

    // ==================== 对话历史管理（v3.0新增） ====================

    /**
     * 获取对话历史
     *
     * GET /api/v1/ai/dialogs?limit=20
     *
     * @param limit 返回数量限制
     * @return 对话历史列表
     */
    @GetMapping("/dialogs")
    @Operation(summary = "获取对话历史", description = "获取当前用户的对话历史列表")
    public Result<List<AiDialogEntity>> getDialogHistory(
            @RequestParam(value = "limit", required = false) Integer limit) {

        Long userId = getCurrentUserId();

        // 权限检查：ai:view_history
        if (!permissionService.checkPermission(userId, "ai", "view_history")) {
            throw new ForbiddenException("无权限查看对话历史");
        }

        log.info("GET /api/v1/ai/dialogs - userId={}, limit={}", userId, limit);

        List<AiDialogEntity> dialogs = aiService.getDialogHistory(userId, limit);
        return Result.success(dialogs);
    }

    /**
     * 删除单条对话
     *
     * DELETE /api/v1/ai/dialogs/{dialogId}
     *
     * @param dialogId 对话ID
     * @return 成功响应
     */
    @DeleteMapping("/dialogs/{dialogId}")
    @Operation(summary = "删除单条对话", description = "删除指定的对话记录")
    public Result<Void> deleteDialog(@PathVariable Long dialogId) {
        Long userId = getCurrentUserId();

        // 权限检查：ai:delete_conversation
        if (!permissionService.checkPermission(userId, "ai", "delete_conversation")) {
            throw new ForbiddenException("无权限删除对话");
        }

        log.info("DELETE /api/v1/ai/dialogs/{} - userId={}", dialogId, userId);

        aiService.deleteDialog(userId, dialogId);
        return Result.success("对话删除成功");
    }

    /**
     * 清空所有对话历史
     *
     * DELETE /api/v1/ai/dialogs
     *
     * @return 成功响应
     */
    @DeleteMapping("/dialogs")
    @Operation(summary = "清空所有对话历史", description = "删除当前用户的所有对话记录")
    public Result<Void> clearAllDialogs() {
        Long userId = getCurrentUserId();

        // 权限检查：ai:delete_conversation
        if (!permissionService.checkPermission(userId, "ai", "delete_conversation")) {
            throw new ForbiddenException("无权限清空对话历史");
        }

        log.info("DELETE /api/v1/ai/dialogs - userId={}", userId);

        aiService.clearAllDialogs(userId);
        return Result.success("对话历史已清空");
    }

    // ==================== AI反馈（AI-003，合并自FeedbackController） ====================

    /**
     * 提交AI答案反馈
     *
     * POST /api/v1/ai/feedback
     *
     * @param request 反馈请求
     * @return 反馈结果
     */
    @PostMapping("/feedback")
    @Operation(
            summary = "提交AI答案反馈",
            description = "对AI答案提交反馈（positive/negative），negative时必须填写原因"
    )
    public Result<AiFeedbackVO> submitFeedback(@Valid @RequestBody SubmitFeedbackRequest request) {
        Long userId = getCurrentUserId();
        log.info("提交反馈：conversationId={}, feedbackType={}, userId={}",
                request.getConversationId(), request.getFeedbackType(), userId);

        AiFeedbackVO feedback = feedbackService.submitFeedback(request, userId);
        return Result.success("反馈提交成功", feedback);
    }

    /**
     * 从Spring Security上下文获取当前用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new UnauthorizedException("未登录或认证已过期");
        }

        Object principal = authentication.getPrincipal();
        if (principal instanceof Long) {
            return (Long) principal;
        }

        throw new UnauthorizedException("无效的认证信息");
    }
}
